import { getToken, getUserName, getUserId } from '@/utils/auth'
import { setToken, setUserName, setUserId } from '@/utils/auth'
import { removeToken, removeUserName, removeUserId } from '@/utils/auth'
import { login } from '@/api/user'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userName: getUserName() || '',
    userId: getUserId() || ''
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUserId(state, userId) {
      state.userId = userId
      setUserId(userId)
    },
    setUserName(state, userName) {
      state.userName = userName
      setUserName(userName)
    },
    logout(state) {
      removeToken()
      removeUserName()
      removeUserId()
    }
  },
  actions: {
    async login(context, data) {
      const res = await login(data)
      if (res.data.token) {
        context.commit('setToken', res.data.token)
        context.commit('setUserId', res.data.userId)
        context.commit('setUserName', res.data.userName)
        Message.success(res.data.msg)
      } else {
        throw new Error(res.data.msg)
      }
    },
    logout({ commit }) {
      commit('logout')
    }
  }
}
